<?php
namespace Common\Oauth;

class Facebook
{
    public $api_url;
    public $redirect_uri;
    public $member_uri;
    private $app_id;
    private $app_secret;
    private $response_type;
    private $authorization_code;

    public function __construct()
    {
        $this->api_url = 'https://graph.facebook.com';
        $this->redirect_uri = C('HTTP_SERVER').'passport/facebook';
        $this->member_uri = C('HTTP_SERVER').'member';
        $this->app_id = '412198975611998';
        $this->app_secret = '9de213b1b83354f3067ac98ac418b760';
        $this->response_type = 'code';
        $this->authorization_code = 'authorization_code';

        /*
        service@nextshe.com

        JS:
        <script>
            window.fbAsyncInit = function() {
                FB.init({
                    appId      : '412198975611998',
                    xfbml      : true,
                    version    : 'v2.2'
                });
            };

            (function(d, s, id){
                var js, fjs = d.getElementsByTagName(s)[0];
                if (d.getElementById(id)) {return;}
                js = d.createElement(s); js.id = id;
                js.src = "//connect.facebook.net/en_US/sdk.js";
                fjs.parentNode.insertBefore(js, fjs);
            }(document, 'script', 'facebook-jssdk'));
        </script>
        */
    }

    //第一步::得到登录链接地址，访问此地址会返回一个 code 在第二步使用
    public function getLoginUrl()
    {
        /*  scope可选择的值：
            user_about_me,user_activities,user_birthday,
            user_education_history,user_events,user_groups,
            user_hometown,user_interests,user_likes,user_location,
            user_notes,user_online_presence,user_photo_video_tags,
            user_photos,user_relationships,user_religion_politics,
            user_status,user_videos,user_website,user_work_history,
            read_friendlists,read_requests,publish_stream,create_event,rsvp_event,sms,offline_access,
            friends_about_me,friends_activities,friends_birthday,
            friends_education_history,friends_events,friends_groups,
            friends_hometown,friends_interests,friends_likes,
            friends_location,friends_notes,friends_online_presence,
            friends_photo_video_tags,friends_photos,friends_relationships,
            friends_religion_politics,friends_status,friends_videos,
            friends_website,friends_work_history,read_stream,photo_upload 
        */
        $params=array(
            'response_type'=>$this->response_type,
            'client_id'=>$this->app_id,
            'redirect_uri'=>$this->redirect_uri,
            'scope'=>'user_about_me,email'
        );
        return $this->api_url.'/oauth/authorize?'.http_build_query($params);
    }

    //第二步::获取 access token ，结果最好存到 session 中，以便其他地方使用
    /*
    正常的 $response 返回值是string，用parse_str()解析出:
    Array
    (
        [access_token] => CAAK7szPTLLsBAGyiF9CTCe9H6iTUj3ypjmfCMUhb7HSTigd11y1oqon1pnGlGFRxZA4sDiXDlrlpLEZC8wUgQBJxwJaUAes1OvnivnjoxSx55LE02HzDYV3CNE9PRgcbNWo6FVQDPEDMtJ4lzFUCBmiXAZCoslZB477MZA45QUb1uHnFhiwgp2vAHKSMYRcJrQGsBzv2gMI5m3cTiBQZAK
        [expires] => 5184000
    )
    */
    public function getAccessToken($code = '')
    {
        $code = trim($code);
        if($code == ''){ return array('st'=>'n', 'msg'=>'Missing Code'); }

        $params = array(
            'grant_type'=>$this->authorization_code,
            'code'=>$code,
            'client_id'=>$this->app_id,
            'client_secret'=>$this->app_secret,
            'redirect_uri'=>$this->redirect_uri
        );
        $response = $this->facebookCurl($this->api_url.'/oauth/access_token', http_build_query($params), 'POST');

        //curl失败
        if($response === false){
            return array('st'=>'n', 'msg'=>'Request Failure');
        }

        //解析字符串
        parse_str($response, $fb_rs);

        if(empty($fb_rs['access_token'])){
            return array('st'=>'n', 'msg'=>$response);
        }

        return array('st'=>'y', 'msg'=>$fb_rs);
    }

    //第三步::调用接口，返回结果是json
    /*
    例如：$this->api('me', array(), 'GET')：通过接口/me，得到当前用户信息
    array(10)
    {
        ["id"] => string(16) "1473779342900633"
        ["email"] => string(20) "liuqianjiu@gmail.com"
        ["first_name"] => string(3) "耳"
        ["gender"] => string(4) "male"
        ["last_name"] => string(3) "刘"
        ["link"] => string(61) "https://www.facebook.com/app_scoped_user_id/1473779342900633/"
        ["locale"] => string(5) "zh_CN"
        ["name"] => string(6) "刘耳"
        ["timezone"] => int(8)
        ["updated_time"] => string(24) "2014-03-24T09:06:27+0000"
        ["verified"] => bool(false)
    }
    */
    public function api($url, $access_token='', $params=array(), $method='GET')
    {
        $url = $this->api_url.$url;
        $params['access_token'] = $access_token;
        if($method == 'GET'){
            $result = $this->facebookCurl($url.'?'.http_build_query($params));
        }else{
            $result = $this->facebookCurl($url, http_build_query($params), 'POST');
        }
        $result = json_decode($result, true);
        if(empty($result)){
            return array('st'=>'n', 'msg'=>'There is something wrong');
        }
        if( ! empty($result['error'])){
            return array('st'=>'n', 'msg'=>json_encode($result));
        }
        return array('st'=>'y', 'msg'=>$result);
    }

    //工具::Curl
    public function facebookCurl($url, $postFields='', $method='GET', $headers=array())
    {
        $ci = curl_init();
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ci, CURLOPT_TIMEOUT, 30);
        if($method == 'POST'){
            curl_setopt($ci, CURLOPT_POST, TRUE);
            if($postFields!='')curl_setopt($ci, CURLOPT_POSTFIELDS, $postFields);
        }
        $headers[] = 'User-Agent: Facebook.PHP(Nextshe.co.uk)';
        curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ci, CURLOPT_URL, $url);
        $response = curl_exec($ci);
        curl_close($ci);
        return $response;
    }
}